﻿using AutoMapper;
using MediatR;
using Traceability.API.Applications.Command.SlaughterCommand;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.Applications.CommandHandler.SlaughterCommandHandler
{
    public class SlaughterHouseAddCommandHandler : IRequestHandler<SlaughterHouseAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Slaughter_House> _houseRepository;
        private readonly IMapper mapper;

        public SlaughterHouseAddCommandHandler(IBaseRepository<Slaughter_House> houseRepository, IMapper mapper)
        {
            _houseRepository = houseRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(SlaughterHouseAddCommand request, CancellationToken cancellationToken)
        {
            var res = mapper.Map<Slaughter_House>(request);
            if (request.Id != 0)
            {
                res.UpDataUserId = request.CreateUserId;
                res.UpDataTime = DateTime.Now;
            }
            int count=await _houseRepository.Update(res);
            APIResult<int> aPIResult = new APIResult<int>();
            if (count > 0)
            {
                aPIResult.Code = EnumCode.Ok;
                aPIResult.Data = count;
                aPIResult.Msg = "保存成功";
            }
            else
            {
                aPIResult.Code = EnumCode.File;
                aPIResult.Data = count;
                aPIResult.Msg = "保存失败";
            }
            return await Task.FromResult(aPIResult);
        }
    }
}
